import React, { Component } from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { WeaTableNew } from 'comsMobx';
import { Radio, message } from 'antd';
import { WeaTab, WeaLocaleProvider, WeaButtonIcon } from 'ecCom';
import { AntdConfirm } from '../util';
import Edit from './Edit';

const { WeaTable } = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;
const MAILPAGENAME = 'SIGN';

@inject('settingStore')
@observer
class Sign extends Component {
  static defaultProps = {
    prefixCls: 'email-setting-sign',
  };

  constructor(props) {
    super(props);
    this.state = {
      editVisible: false,
    };
  }

  componentWillMount() {
    const {
      settingStore: { signStore, setStoreState },
    } = this.props;
    let rightMenuDatas = [
      {
        key: 'refresh',
        icon: <i className="icon-coms-Update-synchronization" />,
        content: getLabel(197, '搜索'),
        onClick: () => signStore.getMailSign(),
      },
    ];
    setStoreState({ rightMenuDatas });
    signStore.getMailSign();
  }

  componentWillUnmount() {
    const {
      settingStore: { signStore },
    } = this.props;
    signStore.clear();
  }

  radioChange = (e, record) => {
    const {
      settingStore: { signStore },
    } = this.props;
    let defaultSignId = record.randomFieldId;
    signStore
      .operateUserMailSign({ operation: 'default', defaultSignId })
      .then((res) => {
        if (res.flag) {
          signStore.getMailSign(true);
        }
      });
  };

  getColumns = (columns) => {
    let newColumns = '';
    newColumns = columns.map((column) => {
      let newColumn = column;
      newColumn.render = (text, record) => {
        // 前端元素转义
        let valueSpan =
          record[`${newColumn.dataIndex}span`] !== undefined
            ? record[`${newColumn.dataIndex}span`]
            : record[newColumn.dataIndex];
        if (newColumn.dataIndex === 'id') {
          return (
            <Radio
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Radio@94p7vm@${MAILPAGENAME}${record.randomFieldId}`}
              type="checkbox"
              checked={record.isDefault * 1 === 1}
              onChange={e => this.radioChange(e, record)}
            />
          );
        } else if (newColumn.dataIndex == 'signName') {
          return (
            <a
              onClick={() => this.editSign(record)}
              dangerouslySetInnerHTML={{ __html: valueSpan }}
            />
          );
        }
        return <div dangerouslySetInnerHTML={{ __html: valueSpan }} />;
      };
      return newColumn;
    });
    return newColumns;
  };

  onOperatesClick = (record, index, operate) => {
    if (operate.index === '0') {
      // edit
      this.editSign(record);
    } else if (operate.index === '1') {
      // delete
      this.batchDel(record.randomFieldId);
    }
  };

  batchDel = (id) => {
    const {
      settingStore: { signStore },
    } = this.props;
    const { operateUserMailSign, signTable } = signStore;
    const ids = id || toJS(signTable.selectedRowKeysAllPages).join();
    AntdConfirm('', () => {
      operateUserMailSign({ ids, operation: 'delete' }).then((res) => {
        if (res.flag) {
          message.success(getLabel(83472, '删除成功！'));
          signStore.getMailSign();
        } else {
          message.error(getLabel(384401, '删除失败，请重试！'));
        }
      });
    });
  };

  editSign = (record) => {
    const {
      settingStore: { signStore },
    } = this.props;
    const {
      getEmailSignCondition,
      getMailSignEntity,
      setStoreState,
    } = signStore;
    this.setState({ editVisible: true });
    getEmailSignCondition({ type: 'update' }, () => {
      getMailSignEntity(
        { id: record.randomFieldId, signType: record.signType },
        () => {
          setStoreState({
            editTitle: getLabel(384457, '编辑签名'),
            editType: 'edit',
            editId: record.randomFieldId,
          });
        },
      );
    });
  };

  onEditCancel = () => this.setState({ editVisible: false });
  onEditSubmit = () => {
    const {
      settingStore: { signStore },
    } = this.props;
    signStore.getMailSign(true);
  };
  onAddSign = () => {
    this.setState({ editVisible: true });
    this.refs.editSign.wrappedInstance.newSign();
  };

  render() {
    const {
      prefixCls,
      settingStore: { signStore },
    } = this.props;
    const { signTable } = signStore;
    const tabButtons = [
      <WeaButtonIcon
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaButtonIcon@bbpu4x@${MAILPAGENAME}add`}
        buttonType="add"
        type="primary"
        onClick={this.onAddSign}
      />,
      <WeaButtonIcon
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaButtonIcon@b15ol1@${MAILPAGENAME}del`}
        buttonType="del"
        type="primary"
        disabled={toJS(signTable.selectedRowKeysAllPages).length === 0}
        onClick={() => this.batchDel()}
      />,
    ];
    return (
      <div className={prefixCls}>
        <WeaTab
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaTab@11fape`}
          datas={[{ title: getLabel(384456, '签名列表'), viewcondition: '0' }]}
          keyParam="viewcondition"
          buttons={tabButtons}
        />
        <WeaTable
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaTable@zo0r8l`}
          comsWeaTableStore={signTable}
          getColumns={this.getColumns}
          onOperatesClick={this.onOperatesClick}
          hasOrder
          needScroll
        />
        <Edit
          ecId={`${(this && this.props && this.props.ecId) || ''}_Edit@4m6qvu`}
          ref="editSign"
          visible={this.state.editVisible}
          onCancel={this.onEditCancel}
          onSubmit={this.onEditSubmit}
        />
      </div>
    );
  }
}

export default Sign;
